import React, { useRef, useState, useCallback, useEffect } from 'react';
import { Button, message, Modal, Spin, Progress, Typography, Space, Row, Col } from 'antd';
import { CameraOutlined, ReloadOutlined, CheckCircleOutlined, LoadingOutlined, WarningOutlined, InfoCircleOutlined } from '@ant-design/icons';
import Webcam from 'react-webcam';
import './index.scss';

const { Text, Title } = Typography;

const FaceCapture = ({ onCapture, disabled }) => {
  const webcamRef = useRef(null);
  const canvasRef = useRef(null);
  const [isStreaming, setIsStreaming] = useState(false);
  const [capturedImage, setCapturedImage] = useState(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [faceDetected, setFaceDetected] = useState(false);
  const [faceConfidence, setFaceConfidence] = useState(0);
  const [processingCapture, setProcessingCapture] = useState(false);
  const [cameraError, setCameraError] = useState(null);
  const [lightLevel, setLightLevel] = useState('unknown');
  const [facingUser, setFacingUser] = useState(true); // 默认使用前置摄像头
  const [key, setKey] = useState(0); // 添加key来强制重新渲染Webcam组件
  const [showPreview, setShowPreview] = useState(false); // 添加预览状态
  const [showFlash, setShowFlash] = useState(false); // 添加闪光效果状态

  // Face detection simulation with more realistic behavior
  useEffect(() => {
    let detectionInterval;
    if (isStreaming && webcamRef.current && webcamRef.current.video && !processingCapture) {
      detectionInterval = setInterval(() => {
        // Get light level (simplified simulation)
        if (webcamRef.current && webcamRef.current.video && webcamRef.current.video.readyState === 4) {
          const canvas = document.createElement('canvas');
          const context = canvas.getContext('2d');
          canvas.width = 50; // Small sample for light detection
          canvas.height = 50;
          context.drawImage(webcamRef.current.video, 0, 0, 50, 50);
          
          try {
            const imageData = context.getImageData(0, 0, 50, 50).data;
            let totalBrightness = 0;
            
            // Calculate average brightness
            for (let i = 0; i < imageData.length; i += 4) {
              const r = imageData[i];
              const g = imageData[i + 1];
              const b = imageData[i + 2];
              totalBrightness += (r + g + b) / 3;
            }
            
            const avgBrightness = totalBrightness / (imageData.length / 4);
            
            // Update light level based on brightness
            if (avgBrightness < 40) {
              setLightLevel('low');
            } else if (avgBrightness > 200) {
              setLightLevel('high');
            } else {
              setLightLevel('good');
            }
            
            // Light affects face detection probability
            let detectionProbability = 0.95;
            
            if (lightLevel === 'low') {
              detectionProbability = 0.9;
            } else if (lightLevel === 'good') {
              detectionProbability = 1.0;
            }
            
            // Simulate face detection with adjusted probability
            const detected = Math.random() <= detectionProbability;
            setFaceDetected(detected);
            
            if (detected) {
              // Generate a confidence value between 75-100%
              // Better light gives higher confidence
              const baseConfidence = lightLevel === 'good' ? 85 : (lightLevel === 'low' ? 75 : 80);
              const variance = 15;
              const confidence = Math.min(100, Math.floor(baseConfidence + (Math.random() * variance)));
              setFaceConfidence(confidence);
            } else {
              setFaceConfidence(0);
            }
          } catch (e) {
            console.error('Error analyzing video frame:', e);
          }
        }
      }, 500);
    }
    
    return () => {
      if (detectionInterval) clearInterval(detectionInterval);
    };
  }, [isStreaming, lightLevel, processingCapture]);

  // 处理闪光效果
  useEffect(() => {
    if (showFlash) {
      const timer = setTimeout(() => {
        setShowFlash(false);
      }, 500);
      
      return () => clearTimeout(timer);
    }
  }, [showFlash]);

  const startCamera = useCallback(() => {
    try {
      setCameraError(null);
      setModalVisible(true);
      setIsStreaming(true);
      setShowPreview(false);
      setShowFlash(false);
      // 增加一个key值，强制重新渲染Webcam组件
      setKey(prevKey => prevKey + 1);
    } catch (error) {
      console.error('Camera access error:', error);
      setCameraError(
        error.name === 'NotAllowedError' 
          ? '摄像头访问被拒绝，请允许浏览器访问摄像头' 
          : '无法访问摄像头，请检查设备连接'
      );
      message.error('无法访问摄像头，请检查权限设置');
    }
  }, []);

  const stopCamera = useCallback(() => {
    // 确保停止所有视频流
    if (webcamRef.current && webcamRef.current.video && webcamRef.current.video.srcObject) {
      const tracks = webcamRef.current.video.srcObject.getTracks();
      tracks.forEach(track => track.stop());
    }
    setIsStreaming(false);
    setModalVisible(false);
    setFaceDetected(false);
    setFaceConfidence(0);
    setShowPreview(false);
    setShowFlash(false);
  }, []);

  const capturePhoto = useCallback(() => {
    if (webcamRef.current && canvasRef.current) {
      // 移除对人脸检测的要求
      // if (!faceDetected) {
      //   message.warning('请确保您的脸部在画面中，并等待人脸检测成功');
      //   return;
      // }
      
      setProcessingCapture(true);
      // 触发闪光效果
      setShowFlash(true);
      
      try {
        // 先获取截图，确保在处理前已经捕获到图像
        const imageSrc = webcamRef.current.getScreenshot();
        
        if (!imageSrc) {
          message.error('无法获取照片，请检查摄像头是否正常工作');
          setProcessingCapture(false);
          return;
        }
        
        // 短暂延迟以显示闪光效果
        setTimeout(() => {
          // 创建临时图像用于预览
          const tempImage = new Image();
          tempImage.onload = () => {
            const canvas = canvasRef.current;
            const context = canvas.getContext('2d');
            
            canvas.width = tempImage.width;
            canvas.height = tempImage.height;
            context.drawImage(tempImage, 0, 0);
            
            // 添加水印
            context.font = '14px Arial';
            context.fillStyle = 'rgba(255, 255, 255, 0.5)';
            const timestamp = new Date().toLocaleString();
            context.fillText(`拍摄时间: ${timestamp}`, 10, canvas.height - 10);
            
            // 显示预览
            setShowPreview(true);
            
            // 延迟处理，让用户看到拍照效果
            setTimeout(() => {
              const imageData = canvas.toDataURL('image/jpeg', 0.8);
              setCapturedImage(imageData);
              
              if (onCapture) {
                // Remove data:image/jpeg;base64, prefix
                onCapture(imageData.split(',')[1]);
              }
              
              // 处理完成后再停止相机
              stopCamera();
              setProcessingCapture(false);
              message.success('人脸照片拍摄成功！');
            }, 1000);
          };
          
          tempImage.src = imageSrc;
        }, 100);
      } catch (error) {
        console.error('Image capture error:', error);
        setProcessingCapture(false);
        setShowFlash(false);
        message.error('照片拍摄失败，请重试');
      }
    }
  }, [onCapture, stopCamera]);

  const retakePhoto = useCallback(() => {
    setCapturedImage(null);
    setShowPreview(false);
    setShowFlash(false);
    startCamera();
  }, [startCamera]);

  const toggleCamera = useCallback(() => {
    // 切换相机方向
    setFacingUser(!facingUser);
    // 增加一个key值，强制重新渲染Webcam组件
    setKey(prevKey => prevKey + 1);
  }, [facingUser]);

  const getLightLevelStatus = () => {
    if (lightLevel === 'low') {
      return (
        <div className="light-status warning">
          <WarningOutlined />
          <Text type="warning">光线较暗，但仍可拍照</Text>
        </div>
      );
    } else if (lightLevel === 'high') {
      return (
        <div className="light-status warning">
          <WarningOutlined />
          <Text type="warning">光线较亮，可能导致过曝</Text>
        </div>
      );
    } else if (lightLevel === 'good') {
      return (
        <div className="light-status good">
          <CheckCircleOutlined />
          <Text type="success">光线良好</Text>
        </div>
      );
    }
    return null;
  };

  const getFaceDetectionStatus = () => {
    if (!isStreaming) return null;
    
    if (faceDetected) {
      const confidenceLevel = faceConfidence < 70 
        ? '低' 
        : faceConfidence < 85 
          ? '中'
          : '高';
          
      return (
        <div className="face-detection-status detected">
          <CheckCircleOutlined />
          <Text>已检测到人脸 (置信度: {confidenceLevel})</Text>
          <Progress 
            percent={faceConfidence} 
            size="small" 
            status={faceConfidence < 70 ? "exception" : "success"}
            strokeWidth={4}
          />
        </div>
      );
    } else {
      // 在低光环境下显示更积极的提示
      if (lightLevel === 'low') {
        return (
          <div className="face-detection-status warning">
            <LoadingOutlined spin />
            <Text>光线较暗，可能影响检测质量，但您仍可拍照</Text>
          </div>
        );
      }
      
      return (
        <div className="face-detection-status not-detected">
          <LoadingOutlined spin />
          <Text>未检测到人脸，请调整姿势或光线</Text>
        </div>
      );
    }
  };

  const videoConstraints = {
    width: 640,
    height: 480,
    facingMode: facingUser ? "user" : "environment",
    frameRate: { ideal: 30, max: 60 }
  };

  return (
    <div className="face-capture">
      {cameraError ? (
        <div className="camera-error">
          <Text type="danger">{cameraError}</Text>
          <Button onClick={() => setCameraError(null)}>重试</Button>
        </div>
      ) : !capturedImage ? (
        <Button
          type="primary"
          icon={<CameraOutlined />}
          onClick={startCamera}
          disabled={disabled}
          size="large"
          className="capture-button"
        >
          拍摄人脸照片
        </Button>
      ) : (
        <div className="captured-preview">
          <img src={capturedImage} alt="拍摄的人脸照片" className="preview-image" />
          <Button
            icon={<ReloadOutlined />}
            onClick={retakePhoto}
            disabled={disabled}
          >
            重新拍摄
          </Button>
        </div>
      )}

      <Modal
        title="人脸拍摄"
        open={modalVisible}
        onCancel={processingCapture ? undefined : stopCamera}
        footer={[
          <Button key="cancel" onClick={stopCamera} disabled={processingCapture}>
            取消
          </Button>,
          <Button
            key="toggleCamera"
            icon={<ReloadOutlined />}
            onClick={toggleCamera}
            disabled={processingCapture || showPreview}
          >
            切换摄像头
          </Button>,
          <Button
            key="capture" 
            type="primary" 
            onClick={capturePhoto}
            loading={processingCapture}
            disabled={processingCapture || showPreview}
          >
            立即拍摄
          </Button>,
        ]}
        width={700}
        centered
        destroyOnClose={true}
        maskClosable={!processingCapture}
        closable={!processingCapture}
      >
        <div className="camera-container">
          <Spin spinning={!isStreaming && !showPreview} tip="正在启动摄像头...">
            <div className="video-container">
              {showFlash && <div className="camera-flash" />}
              
              {isStreaming && !showPreview && (
                <Webcam
                  key={key}
                  ref={webcamRef}
                  audio={false}
                  screenshotFormat="image/jpeg"
                  videoConstraints={videoConstraints}
                  className="camera-video"
                  mirrored={facingUser}
                  onUserMedia={() => setIsStreaming(true)}
                  onUserMediaError={(error) => {
                    console.error('Webcam error:', error);
                    setCameraError(
                      error.name === 'NotAllowedError' 
                        ? '摄像头访问被拒绝，请允许浏览器访问摄像头' 
                        : '无法访问摄像头，请检查设备连接'
                    );
                    setIsStreaming(false);
                  }}
                />
              )}
              {showPreview && canvasRef.current && (
                <div className="preview-container">
                  <img 
                    src={canvasRef.current.toDataURL('image/jpeg')} 
                    alt="预览照片" 
                    className="preview-image-modal" 
                  />
                  <div className="preview-message">
                    <LoadingOutlined spin style={{ marginRight: 8 }} />
                    <Text>正在处理照片...</Text>
                  </div>
                </div>
              )}
              <canvas ref={canvasRef} style={{ display: 'none' }} />
            </div>
          </Spin>
          
          {!showPreview && (
            <>
              <Row gutter={[16, 16]} className="status-indicators">
                <Col span={12}>
                  {getFaceDetectionStatus()}
                </Col>
                <Col span={12}>
                  {getLightLevelStatus()}
                </Col>
              </Row>
              
              <div className="camera-tips">
                <InfoCircleOutlined />
                <Space direction="vertical">
                  <Text type="secondary">请将脸部置于画面中央，确保光线充足</Text>
                  <Text type="secondary">保持面部正对摄像头，不要倾斜或遮挡面部</Text>
                  <Text type="secondary">拍摄时请勿移动，以确保照片清晰</Text>
                </Space>
              </div>
            </>
          )}
        </div>
      </Modal>
    </div>
  );
};

export default FaceCapture;